package com.example.demo.main.rabbitmq.exchange.topic;

import com.example.demo.main.rabbitmq.utils.RabbitmqConnectionUtil;
import com.rabbitmq.client.*;

import java.nio.charset.StandardCharsets;

/**
 * @author xieluoyin
 */
public class Consumer4TopicExchange {

    public static void main(String[] args) throws Exception {


        Connection connection = RabbitmqConnectionUtil.getConnection();

        Channel channel = connection.createChannel();
        //4 声明
        String exchangeName = "test_topic_exchange";
        String exchangeType = "topic";
        String queueName = "test_topic_queue";
        //String routingKey = "user.*";
        String routingKey = "user.*";
        // 1 声明交换机
        channel.exchangeDeclare(exchangeName, exchangeType, true, false, false, null);
        // 2 声明队列
        channel.queueDeclare(queueName, false, false, false, null);
        // 3 建立交换机和队列的绑定关系:
        channel.queueBind(queueName, exchangeName, routingKey);

        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) {

                String message = new String(body, StandardCharsets.UTF_8);
                System.out.println(" [Consumer routingKey="+routingKey+ "] Received '" + message + "'");
            }
        };

        //参数：队列名称、是否自动ACK、Consumer
        channel.basicConsume(queueName, true, consumer);
    }
}
